'use strict';
const _ = require('lodash');
const path = require('path');
const {Controller} = require('ee-core');
const {
    app: electronApp, dialog, shell, Notification, clipboard,
    powerMonitor, screen, nativeTheme,
} = require('electron');
const {session, Menu, app} = require('electron');
const Conf = require('ee-core/config');
const Ps = require('ee-core/ps');
const Services = require('ee-core/services');
const Addon = require('ee-core/addon');
const { machineId, machineIdSync } = require('node-machine-id');
const https = require('https');
/**
 * 操作系统 - 功能demo
 * @class
 */
class OsController extends Controller {

    constructor(ctx) {
        super(ctx);
    }

    /**
     * 所有方法接收两个参数
     * @param args 前端传的参数
     * @param event - ipc通信时才有值。详情见：控制器文档
     */

    /**
     * 消息提示对话框
     */
    messageShow() {
        dialog.showMessageBoxSync({
            type: 'info', // "none", "info", "error", "question" 或者 "warning"
            title: '自定义标题-message',
            message: '自定义消息内容',
            detail: '其它的额外信息'
        })

        return '打开了消息框';
    }

    /**
     * 消息提示与确认对话框
     */
    messageShowConfirm() {
        const res = dialog.showMessageBoxSync({
            type: 'info',
            title: '自定义标题-message',
            message: '自定义消息内容',
            detail: '其它的额外信息',
            cancelId: 1, // 用于取消对话框的按钮的索引
            defaultId: 0, // 设置默认选中的按钮
            buttons: ['确认', '取消'], // 按钮及索引
        })
        let data = (res === 0) ? '点击确认按钮' : '点击取消按钮';

        return data;
    }

    /**
     * 选择目录
     */
    selectFolder() {
        const filePaths = dialog.showOpenDialogSync({
            properties: ['openDirectory', 'createDirectory']
        });

        if (_.isEmpty(filePaths)) {
            return null
        }

        return filePaths[0];
    }

    /**
     * 打开目录
     */
    openDirectory(args) {
        if (!args.id) {
            return false;
        }
        let dir = '';
        if (path.isAbsolute(args.id)) {
            dir = args.id;
        } else {
            dir = electronApp.getPath(args.id);
        }

        shell.openPath(dir);
        return true;
    }

    /**
     * 加载视图内容
     */
    loadViewContent(args) {
        const {type, content} = args;
        let contentUrl = content;
        if (type == 'html') {
            contentUrl = path.join('file://', electronApp.getAppPath(), content);
        }

        Services.get('os').createBrowserView(contentUrl);

        return true
    }

    /**
     * 移除视图内容
     */
    removeViewContent() {
        Services.get('os').removeBrowserView();
        return true
    }


    //获取当前设备id
    getMyUUID(){
        return machineIdSync()
    }


    /**
     * 打开新窗口
     */
    /**
     * 打开新窗口
     */
    createWindow(args) {
        const {type, content, windowName, windowTitle, noAdd, state, cookie,rowId} = args;
        let contentUrl = null;
        let cookieString = cookie
        // 确定内容 URL 地址
        if (type === 'html') {
            contentUrl = path.join('file://', electronApp.getAppPath(), content);
        } else if (type === 'web') {
            contentUrl = content;
        } else if (type === 'vue') {
            // 根据环境确定 Vue 的加载地址
            let addr = Ps.isProd()
                ? Conf.isFileProtocol(Conf.getValue('mainServer'))
                    ? path.join(Ps.getHomeDir(), Conf.getValue('mainServer').indexPath)
                    : Conf.getValue('mainServer').protocol + Conf.getValue('mainServer').host + ':' + Conf.getValue('mainServer').port
                : 'http://localhost:8080';
            contentUrl = addr + content;
        }

        // 创建独立的 session
        const sessionName = `persist:${Math.random()}`;
        let tsession = session.fromPartition(sessionName);
        if (cookieString === undefined || cookieString.length === 0) {
            cookieString = '_lxsdk_cuid=18f9ec8114ec8-0d7c551b160fad-26001d51-1fa400-18f9ec8114ec8';
        }
        const cookies = [];
        let cookieArray = cookieString.split(';').map(cookie => cookie.trim());
        cookieArray.forEach(cookie => {
            let [name, value] = cookie.split('=');
            cookies.push({name: name, value: value, url: contentUrl},)
        });
        // 要设置的多个 Cookie
        // 创建窗口
        const win = Addon.get('window').create(windowName || "窗口", {
            title: windowTitle,
            webPreferences: {session: tsession}
        });

        // 循环添加 cookie 并在完成后刷新页面
        Promise.all(cookies.map(cookie => tsession.cookies.set(cookie)))
            .then(() => {
                console.log("All cookies set successfully");
                win.loadURL(contentUrl);  // 加载页面
            })
            .catch(err => {
                console.error("Failed to set one or more cookies", err);
            });

        // 创建开发者工具和菜单
        const menu = Menu.buildFromTemplate([
            {
                label: '控制',
                submenu: [
                    {
                        label: '显示控制台',
                        accelerator: 'F12',
                        click: () => win.webContents.toggleDevTools()
                    },
                    {
                        label: '获取神秘代码',
                        accelerator: 'CmdOrCtrl+T',
                        click: () => win.webContents.executeJavaScript('document.cookie').then(result => clipboard.writeText(result))
                    },
                ]
            },
            {
                label: '保存窗口',
                accelerator: 'Ctrl+S',
                click: () => win.webContents.executeJavaScript('document.cookie').then(async cookie => {
                    if (rowId === "-1") {
                        console.log("当前窗口无归属id");
                    }
                    // 同步获取
                    const idSync = machineIdSync();
                    let data = {
                        deviceId: idSync,
                        id: rowId,
                        windowCookie: cookie
                    };

                    // 使用 https 模块发送 POST 请求
                    const postData = JSON.stringify(data);
                    const options = {
                        hostname: 'api.cangshu-erp.com',
                        port: 443,
                        path: '/public/api/app/updateWindow',
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Content-Length': Buffer.byteLength(postData)
                        }
                    };

                    const req = https.request(options, (res) => {
                        let responseBody = '';
                        res.on('data', (chunk) => {
                            responseBody += chunk;
                        });
                        res.on('end', () => {
                            console.log('Response:', responseBody);
                        });
                    });

                    req.on('error', (e) => {
                        console.error('Request error:', e.message);
                    });

                    // Write data to request body
                    req.write(postData);
                    req.end();
                })
            },
            {
                label: '刷新', // 添加刷新功能
                accelerator: 'F5',  // 设置快捷键为 Ctrl+R 或 Cmd+R
                click: () => win.reload()  // 执行刷新操作
            }
        ]);
        win.setMenu(menu);

  /*      // 监听关闭事件，阻止窗口直接关闭
        win.on('close', event => {
            event.preventDefault();
            win.hide(); // 隐藏窗口而不是关闭
        });*/

        // 将窗口加入全局管理
        if (!noAdd) {
            global.windowMap.add(`${windowName || "窗口"}-${win.webContents.id}`, win, this.formatDate(new Date()), state);
        }

        return `${windowName || "窗口"}-${win.webContents.id}`;
    }


    getWindowMap(type) {
        let ids = global.windowMap.getList(type);
        return ids
    }

    openWindow(args) {
    /*    let window = global.windowMap.getWindow(id)
        window.show();*/
        //新的关闭就是关闭，新的打开就是创建
       this.createWindow(args)

    }

    delWindow(id) {
        global.windowMap.removeById(id)
    }

    updateName(bean) {
        global.windowMap.updateName(bean.id, bean.name)
    }

    formatDate(date) {
        const pad = (num) => num.toString().padStart(2, '0');

        const year = date.getFullYear();
        const month = pad(date.getMonth() + 1); // 月份从 0 开始，所以需要加 1
        const day = pad(date.getDate());
        const hours = pad(date.getHours());
        const minutes = pad(date.getMinutes());
        const seconds = pad(date.getSeconds());

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    /**
     * 获取窗口contents id
     */
    getWCid(args) {
        // 主窗口的name默认是main，其它窗口name开发者自己定义
        const name = args;
        const id = Addon.get('window').getWCid(name);

        return id;
    }

    /**
     * 加载扩展程序
     */
    // async loadExtension (args) {
    //   const crxFile = args[0];
    //   if (_.isEmpty(crxFile)) {
    //     return false;
    //   }
    //   const extensionId = path.basename(crxFile, '.crx');
    //   const chromeExtensionDir = chromeExtension.getDirectory();
    //   const extensionDir = path.join(chromeExtensionDir, extensionId);

    //   Log.info("[api] [example] [loadExtension] extension id:", extensionId);
    //   unzip(crxFile, extensionDir).then(() => {
    //     Log.info("[api] [example] [loadExtension] unzip success!");
    //     chromeExtension.load(extensionId);
    //   });

    //   return true;
    // }

    /**
     * 创建系统通知
     */
    sendNotification(args, event) {
        const {title, subtitle, body, silent} = args;

        if (!Notification.isSupported()) {
            return '当前系统不支持通知';
        }

        let options = {};
        if (!_.isEmpty(title)) {
            options.title = title;
        }
        if (!_.isEmpty(subtitle)) {
            options.subtitle = subtitle;
        }
        if (!_.isEmpty(body)) {
            options.body = body;
        }
        if (!_.isEmpty(silent)) {
            options.silent = silent;
        }

        Services.get('os').createNotification(options, event);

        return true
    }

    /**
     * 电源监控
     */
    initPowerMonitor(args, event) {
        const channel = 'controller.os.initPowerMonitor';
        powerMonitor.on('on-ac', (e) => {
            let data = {
                type: 'on-ac',
                msg: '接入了电源'
            }
            event.reply(`${channel}`, data)
        });

        powerMonitor.on('on-battery', (e) => {
            let data = {
                type: 'on-battery',
                msg: '使用电池中'
            }
            event.reply(`${channel}`, data)
        });

        powerMonitor.on('lock-screen', (e) => {
            let data = {
                type: 'lock-screen',
                msg: '锁屏了'
            }
            event.reply(`${channel}`, data)
        });

        powerMonitor.on('unlock-screen', (e) => {
            let data = {
                type: 'unlock-screen',
                msg: '解锁了'
            }
            event.reply(`${channel}`, data)
        });

        return true
    }

    /**
     * 获取屏幕信息
     */
    getScreen(args) {
        let data = [];
        let res = {};
        if (args == 0) {
            let res = screen.getCursorScreenPoint();
            data = [
                {
                    title: '横坐标',
                    desc: res.x
                },
                {
                    title: '纵坐标',
                    desc: res.y
                },
            ]

            return data;
        }
        if (args == 1) {
            res = screen.getPrimaryDisplay();
        }
        if (args == 2) {
            let resArr = screen.getAllDisplays();
            // 数组，只取一个吧
            res = resArr[0];
        }
        // Log.info('[electron] [ipc] [example] [getScreen] res:', res);
        data = [
            {
                title: '分辨率',
                desc: res.bounds.width + ' x ' + res.bounds.height
            },
            {
                title: '单色显示器',
                desc: res.monochrome ? '是' : '否'
            },
            {
                title: '色深',
                desc: res.colorDepth
            },
            {
                title: '色域',
                desc: res.colorSpace
            },
            {
                title: 'scaleFactor',
                desc: res.scaleFactor
            },
            {
                title: '加速器',
                desc: res.accelerometerSupport
            },
            {
                title: '触控',
                desc: res.touchSupport == 'unknown' ? '不支持' : '支持'
            },
        ]

        return data;
    }

    /**
     * 获取系统主题
     */
    getTheme() {
        let theme = 'system';
        if (nativeTheme.shouldUseHighContrastColors) {
            theme = 'light';
        } else if (nativeTheme.shouldUseInvertedColorScheme) {
            theme = 'dark';
        }

        return theme;
    }

    /**
     * 设置系统主题
     */
    setTheme(args) {

        // TODO 好像没有什么明显效果
        nativeTheme.themeSource = args;

        return args;
    }
}

OsController.toString = () => '[class OsController]';
module.exports = OsController;
